import React, { useState, useEffect } from 'react';
import useStore from '../../components/useStore';
import { Button, Card, Col, Empty, Form, notification, Row, Divider, Collapse, Tooltip } from 'antd';
import { InfoCircleOutlined, DownloadOutlined } from '@ant-design/icons';
import BraftEditor from 'braft-editor';
import 'braft-editor/dist/index.css';
import store from '../../untils/store';
import request from '../../untils/request';

const { Panel } = Collapse;

// 通用请求函数封装
const fetchData = async (url, data, showSuccess = true) => {
  try {
    const result = await request(url, {
      method: "POST",
      mode: 'cors',
      body: data
    });
    if (result.code === 200) {
      if (showSuccess && result.msg) {
        notification.success({ message: result.msg });
      }
      return result;
    } else {
      notification.error({ message: result.msg || "获取数据失败" });
      return null;
    }
  } catch (error) {
    notification.error({ message: "网络请求异常" });
    return null;
  }
};

// 长文本显示组件 - 处理右侧内容
const LongTextDisplay = ({ text, placeholder }) => {
  const displayText = text || placeholder;
  
  return (
    <Tooltip title={displayText} placement="topLeft" mouseEnterDelay={0.3}>
      <div style={styles.contentContainer}>
        {displayText}
      </div>
    </Tooltip>
  );
};

// 标签显示组件 - 处理左侧label，支持省略号和悬停提示
const LabelDisplay = ({ label }) => (
  <Tooltip title={label} placement="topRight" mouseEnterDelay={0.3}>
    <div style={styles.labelContainer}>
      {label}
    </div>
  </Tooltip>
);

// 转换是否维保的值为文本
const formatIsMw = (value) => {
  if (value === undefined || value === null) return '未设置';
  return value === 1 ? '是' : '否';
};

// 转换售后人员ID为名称
const formatAfterSalesPerson = (userId, users) => {
  if (!userId) return '未分配';
  const user = users.find(u => u.value === userId);
  return user ? user.label : `ID: ${userId}`;
};

const ShowAfterSales = () => {
  const { collapsed } = useStore();
  const { localUrl } = store();
  const [form] = Form.useForm();
  const [detail, setDetail] = useState(null);
  const [afterSalesUsers, setafterSalesUsers] = useState([]);
  const [loading, setLoading] = useState(true);

  // 获取售后人员列表
  const fetchAfterSalesUsers = async () => {
    try {
      const data = await request("/admin/user/getAfterSalesUsers", {
        mode: 'cors'
      });
      setafterSalesUsers(data);
    } catch (error) {
      notification.error("售后人员获取失败~")
    }
  };

  // 获取详情数据
  const fetchDetail = async (id) => {
    setLoading(true);
    const result = await fetchData("/admin/afterSales/getAfterSalesInfo", { id }, false);
    
    if (result) {
      // 处理富文本字段
      const formattedData = {
        ...result.data,
        main_problem_content_html: BraftEditor.createEditorState(result.data.main_problem_content_html || ''),
        specific_solution_measures_html: BraftEditor.createEditorState(result.data.specific_solution_measures_html || '')
      };
      setDetail(formattedData);
      form.setFieldsValue(formattedData);
    } else {
      setDetail(null);
    }
    
    setLoading(false);
  };

  // 渲染富文本编辑器 - 保持不变
  const renderBraftEditor = (label, name) => (
    <Form.Item
      name={name}
      label={<LabelDisplay label={label} />}
      labelCol={{ span: 6 }}
      wrapperCol={{ span: 18 }}
      extra="为了方便查看，您可以对该文本进行放大字体，特殊标记等，这不会对数据产生改变。"
    >
      <BraftEditor
        excludeControls={["media"]}
        value={form.getFieldValue(name) || BraftEditor.createEditorState('')}
        onChange={(editorState) => {
          form.setFieldValue(name, editorState);
        }}
        style={{ height: '10vh !important', border: '1px solid gray' }}
      />
    </Form.Item>
  );

  // 页面加载时获取详情和售后人员列表
  useEffect(() => {
    // 先获取售后人员列表
    fetchAfterSalesUsers();
    
    // 从hash中获取ID参数
    const hash = window.location.hash.slice(1);
    const queryString = hash.split('?')[1];
    let id = null;
    
    if (queryString) {
      const queryParams = new URLSearchParams(queryString);
      const idStr = queryParams.get('id');
      // 解析为整数
      id = idStr ? parseInt(idStr, 10) : null;
    } 
    
    if (id) {
      fetchDetail(id);
    } else {
      notification.error({ message: "未找到售后服务单ID参数" });
      setLoading(false);
    }
  }, []);

  if (loading) {
    return (
      <div style={styles.loadingContainer}>
        <div>加载中...</div>
      </div>
    );
  }

  return (
    <div style={{
      height: "94%",
      backgroundColor: `#F1F1F1`,
      right: "1%",
      top: "4vh",
      overflow: "hidden",
      width: collapsed ? "94%" : "84%",
      position: "absolute",
      color: "white",
      fontSize: "0.8rem"
    }}>
      <div style={styles.kshcontainer}>
        <div style={{
          fontSize: "0.7rem",
          position: "relative",
          width: "96%",
          marginLeft: "2%",
          display: "flex",
          textIndent: "1rem",
          justifyContent: "flex-start",
          alignContent: "flex-start",
          flexWrap: "wrap"
        }}>
          <Card 
            title="售后服务单详情" 
            style={{ width: "100%", marginTop: "2vh" }}
          >
            {/* 添加带竖向滚动的容器 */}
            <div style={styles.scrollContainer}>
              {detail === null ? (
                <Empty description="未找到售后服务单信息" />
              ) : (
                <Form
                  style={{ width: "95%", maxWidth: 1000, margin: "0 auto" }}
                  form={form}
                  labelCol={{ span: 6 }}
                  wrapperCol={{ span: 18 }}
                  layout="horizontal"
                >
                  {/* 基础信息区域 */}
                  <div style={{ margin: '20px 0' }}>
                    <h3 style={{ color: '#1890ff', margin: '0 0 12px', fontSize: 16, display: 'flex', alignItems: 'center' }}>
                      <InfoCircleOutlined style={{ marginRight: 6 }} /> 基础信息
                    </h3>
                    <Divider style={{ margin: '0 0 16px' }} />

                    {/* 成对字段 - 第一组 */}
                    <Row gutter={16} style={{ marginBottom: 16 }}>
                      <Col span={12}>
                        <Form.Item name="service_order_id" label={<LabelDisplay label="服务单号" />} style={styles.formItem}>
                          <LongTextDisplay 
                            text={form.getFieldValue('service_order_id')} 
                            placeholder='服务单号为空' 
                          />
                        </Form.Item>
                      </Col>
                      <Col span={12}>
                        <Form.Item name="sn" label={<LabelDisplay label="对应产品SN" />} style={styles.formItem}>
                          <LongTextDisplay 
                            text={form.getFieldValue('sn')} 
                            placeholder='对应产品SN为空' 
                          />
                        </Form.Item>
                      </Col>
                    </Row>

                    {/* 成对字段 - 第二组 */}
                    <Row gutter={16} style={{ marginBottom: 16 }}>
                      <Col span={12}>
                        <Form.Item name="is_mw" label={<LabelDisplay label="是否维保内" />} style={styles.formItem}>
                          <LongTextDisplay 
                            text={formatIsMw(form.getFieldValue('is_mw'))} 
                            placeholder='是否维保内为空' 
                          />
                        </Form.Item>
                      </Col>
                      <Col span={12}>
                        <Form.Item name="service_time" label={<LabelDisplay label="服务时间" />} style={styles.formItem}>
                          <LongTextDisplay 
                            text={form.getFieldValue('service_time')} 
                            placeholder='服务时间为空' 
                          />
                        </Form.Item>
                      </Col>
                    </Row>

                    {/* 成对字段 - 第三组 */}
                    <Row gutter={16} style={{ marginBottom: 16 }}>
                      <Col span={12}>
                        <Form.Item name="contract_number" label={<LabelDisplay label="对应合同号" />} style={styles.formItem}>
                          <LongTextDisplay 
                            text={form.getFieldValue('contract_number')} 
                            placeholder='对应合同号为空' 
                          />
                        </Form.Item>
                      </Col>
                      <Col span={12}>
                        <Form.Item name="sales_order_id" label={<LabelDisplay label="对应销售订单号" />} style={styles.formItem}>
                          <LongTextDisplay 
                            text={form.getFieldValue('sales_order_id')} 
                            placeholder='对应销售订单号为空' 
                          />
                        </Form.Item>
                      </Col>
                    </Row>

                    {/* 单个字段 - 去掉售后人员的解释文本 */}
                    <Row gutter={16} style={{ marginBottom: 16 }}>
                      <Col span={12}>
                        <Form.Item
                          name="after_sales_person_id"
                          label={<LabelDisplay label="售后人员" />}
                          tooltip={{ title: '显示ID号时表明该员工已不属于售后', placement: 'right' }}
                          style={styles.formItem}
                        >
                          <LongTextDisplay 
                            text={formatAfterSalesPerson(form.getFieldValue('after_sales_person_id'), afterSalesUsers)} 
                            placeholder='售后人员为空' 
                          />
                        </Form.Item>
                      </Col>
                      <Col span={12}></Col>
                    </Row>
                  </div>

                  {/* 问题与解决方案折叠面板 - 富文本保持不变 */}
                  <Collapse defaultActiveKey={['1']} style={{ marginBottom: 24 }}>
                    <Panel header="问题与解决方案" key="1">
                      {renderBraftEditor('主要问题内容', 'main_problem_content_html')}
                      {renderBraftEditor('具体解决方案措施', 'specific_solution_measures_html')}
                    </Panel>
                  </Collapse>

                  {/* 费用与物料区域 */}
                  <div style={{ margin: '20px 0' }}>
                    <h3 style={{ color: '#1890ff', margin: '0 0 12px', fontSize: 16, display: 'flex', alignItems: 'center' }}>
                      <InfoCircleOutlined style={{ marginRight: 6 }} /> 费用与物料
                    </h3>
                    <Divider style={{ margin: '0 0 16px' }} />

                    {/* 成对字段 */}
                    <Row gutter={16} style={{ marginBottom: 16 }}>
                      <Col span={12}>
                        <Form.Item name="money" label={<LabelDisplay label="服务费用" />} style={styles.formItem}>
                          <LongTextDisplay 
                            text={form.getFieldValue('money') ? `¥${form.getFieldValue('money')}` : ''} 
                            placeholder='服务费用为空' 
                          />
                        </Form.Item>
                      </Col>
                      <Col span={12}>
                        <Form.Item name="time" label={<LabelDisplay label="工时" />} style={styles.formItem}>
                          <LongTextDisplay 
                            text={form.getFieldValue('time') ? `${form.getFieldValue('time')}小时` : ''} 
                            placeholder='工时为空' 
                          />
                        </Form.Item>
                      </Col>
                    </Row>

                    {/* 单个字段 */}
                    <Row gutter={16}>
                      <Col span={12}>
                        <Form.Item name="need_bom_number" label={<LabelDisplay label="需要替换物料" />} style={styles.formItem}>
                          <LongTextDisplay 
                            text={form.getFieldValue('need_bom_number')} 
                            placeholder='需要替换物料为空' 
                          />
                        </Form.Item>
                      </Col>
                      <Col span={12}></Col>
                    </Row>
                  </div>

                  {/* 附件区域 */}
                  <div style={{ margin: '20px 0' }}>
                    <h3 style={{ color: '#1890ff', margin: '0 0 12px', fontSize: 16, display: 'flex', alignItems: 'center' }}>
                      <InfoCircleOutlined style={{ marginRight: 6 }} /> 相关附件
                    </h3>
                    <Divider style={{ margin: '0 0 16px' }} />

                    {/* 成对附件 */}
                    <Row gutter={16}>
                      <Col span={12}>
                        <Form.Item name="problem_description_list" label={<LabelDisplay label="问题描述清单" />} style={styles.formItem}>
                          {detail?.problem_description_list ? (
                            <a
                              href={`${localUrl}${detail.problem_description_list}`}
                              target="_blank"
                              rel="noopener noreferrer"
                              style={{ color: '#fff' }}
                            >
                              <Button icon={<DownloadOutlined />} type="primary">
                                下载问题描述清单
                              </Button>
                            </a>
                          ) : (
                            <span style={{ color: '#666' }}>
                              <InfoCircleOutlined style={{ fontSize: 14, marginRight: 4, color: '#999' }} />
                              未上传问题描述清单
                            </span>
                          )}
                        </Form.Item>
                      </Col>
                      <Col span={12}>
                        <Form.Item name="problem_solving_solution" label={<LabelDisplay label="问题解决方案" />} style={styles.formItem}>
                          {detail?.problem_solving_solution ? (
                            <a
                              href={`${localUrl}${detail.problem_solving_solution}`}
                              target="_blank"
                              rel="noopener noreferrer"
                              style={{ color: '#fff' }}
                            >
                              <Button icon={<DownloadOutlined />} type="primary">
                                下载问题解决方案
                              </Button>
                            </a>
                          ) : (
                            <span style={{ color: '#666' }}>
                              <InfoCircleOutlined style={{ fontSize: 14, marginRight: 4, color: '#999' }} />
                              未上传问题解决方案
                            </span>
                          )}
                        </Form.Item>
                      </Col>
                    </Row>
                  </div>
                </Form>
              )}
            </div>
          </Card>
        </div>
      </div>
    </div>
  );
};

const styles = {
  kshcontainer: {
    width: "98%",
    height: "95%",
    position: "absolute",
    top: "3%",
    left: "1%",
    backgroundColor: "white",
    color: "black",
    borderRadius: "10px",
  },
  loadingContainer: {
    height: "100%",
    display: "flex",
    justifyContent: "center",
    alignItems: "center",
    fontSize: "1.2rem",
    color: "#333"
  },
  // 滚动容器样式 - 只允许竖向滚动
  scrollContainer: {
    maxHeight: "calc(95vh - 220px)",
    overflowY: "auto",
    overflowX: "hidden",
    padding: "0 16px 16px",
    boxSizing: "border-box",
  },
  // 表单项目整体样式，控制label和内容的间距
  formItem: {
    marginBottom: 16,
  },
  // 左侧标签容器样式 - 支持省略号和悬停提示
  labelContainer: {
    width: "100%",
    whiteSpace: "nowrap",
    overflow: "hidden",
    textOverflow: "ellipsis",
    paddingRight: 8, // 与内容保持一定间距
    fontWeight: 500, // 保持标签的视觉权重
  },
  // 右侧内容容器样式
  contentContainer: {
    width: "100%",
    minHeight: "32px",
    padding: "4px 11px",
    border: "1px solid #d9d9d9",
    borderRadius: "4px",
    backgroundColor: "#f5f5f5",
    color: "rgba(0, 0, 0, 0.65)",
    whiteSpace: "nowrap",
    overflow: "hidden",
    textOverflow: "ellipsis",
    boxSizing: "border-box",
  }
};

export default ShowAfterSales;
